import akshare as ak
import pandas as pd
from datetime import datetime, timedelta


def cal_up_down():
    try:
        # 获取实时行情数据
        df = ak.stock_zh_a_spot_em()

        # 检查数据是否包含关键字段（避免字段名变更）
        if '涨跌幅' not in df.columns:
            raise KeyError("字段 '涨跌幅' 不存在，请检查接口返回的列名")

        # 统计涨跌数量
        up_count = (df['涨跌幅'] > 0).sum()  # 上涨家数
        down_count = (df['涨跌幅'] < 0).sum()  # 下跌家数

        # 获取当前时间
        current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 输出结果
        print(f"更新时间：{current_time}")
        print(f"上涨家数：{up_count}")
        print(f"下跌家数：{down_count}")
        print(f"总股票数：{len(df)}")
        print(f"平盘家数：{len(df) - up_count - down_count}")  # 可选输出

    except Exception as e:
        print(f"发生错误：{str(e)}")


def cal_zt_dt():
    try:
        today = datetime.now()
        yesterday = today - timedelta(days=1)
        stock_zt_pool_em_df = ak.stock_zt_pool_em(date=yesterday.strftime("%Y%m%d"))
        print(stock_zt_pool_em_df)
        stock_zt_pool_dtgc_em_df = ak.stock_zt_pool_dtgc_em(date=yesterday.strftime("%Y%m%d"))
        print(stock_zt_pool_dtgc_em_df)
    except Exception as e:
        print(f"发生错误：{str(e)}")

def get_realtime_zt_count():
    """获取实时涨停家数"""
    try:
        date = datetime.now().strftime("%Y%m%d")
        zt_df = ak.stock_zt_pool_em(date=date)
        return len(zt_df) if not zt_df.empty else 0
    except Exception as e:
        print(f"获取涨停数据异常：{e}")
        return 0

def get_realtime_dt_count():
    """获取实时跌停家数"""
    try:
        date = datetime.now().strftime("%Y%m%d")
        dt_df = ak.stock_zt_pool_dtgc_em(date=date)
        return len(dt_df) if not dt_df.empty else 0
    except Exception as e:
        print(f"获取跌停数据异常：{e}")
        return 0

def get_realtime_zb_count():
    try:
        date = datetime.now().strftime("%Y%m%d")
        zb_df = ak.stock_zt_pool_zbgc_em(date=date)
        return len(zb_df) if not zb_df.empty else 0
    except Exception as e:
        print(f"获取炸板数据异常：{e}")
        return 0

def get_today():
    today = datetime.now()
    # yesterday = today - timedelta(days=1)
    # if today.weekday() == 0:
    #     today -= timedelta(days=3)
    if today.weekday() == 6:
        today -= timedelta(days=2)
    elif today.weekday() == 5:
        today -= timedelta(days=1)
    return today.strftime("%Y%m%d")

def get_yestoday_zt():
    try:
        # 获取昨日涨停数据
        trade_date = get_today()
        limit_df = ak.stock_zt_pool_previous_em(date=trade_date)

        # 新增：过滤北交所股票（通过代码前缀过滤）
        limit_df = limit_df[~limit_df['代码'].str.startswith(('43', '83', '87', '88'))]  # 北交所股票代码前缀为bj

        # 新增：过滤ST股票（通过名称字段）
        limit_df = limit_df[~limit_df['名称'].str.contains('ST', na=False)]  # 包含ST或*ST

        # 统一代码格式（移除sh/sz/bj前缀）
        limit_df['代码'] = limit_df['代码'].str[2:]

        if limit_df.empty:
            raise ValueError("昨日无有效涨停数据（已过滤北交所）")

        first_limit = limit_df[limit_df['昨日连板数'] == 1]
        cont_limit = limit_df[limit_df['昨日连板数'] >= 2]

        # 计算平均值（保留有效数据）
        avg_first = first_limit['涨跌幅'].mean() if not first_limit.empty else 0
        avg_cont = cont_limit['涨跌幅'].mean() if not cont_limit.empty else 0

        print(f"昨日首板数量：{len(first_limit)}（不含北交所）")
        # print(first_limit)
        print(f"昨日连板数量：{len(cont_limit)}（不含北交所）")
        # print(cont_limit)
        print("\n【今日实时统计】")
        print(f"首板平均涨跌幅: {avg_first:.2f}%")
        print(f"连板平均涨跌幅: {avg_cont:.2f}%")
    except Exception as e:
        print(f"获取数据失败: {e}")
        exit()



if __name__ == '__main__':
    cal_up_down()
    get_yestoday_zt()
    zt_count = get_realtime_zt_count()
    dt_count = get_realtime_dt_count()
    zb_count = get_realtime_zb_count()

    print(f"今日涨停家数 {zt_count}")
    print(f"今天跌停家数 {dt_count}")
    print(f"今日炸板家数 {zb_count}")
    print(f"今日封板率 {round(zt_count/(zt_count+zb_count)*100)}%")
